/****************************************************************************
 * Copyright (C) 2012 Dj_Skual
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 ****************************************************************************/
#include "UpdateLanguagesTask.h"
#include "CLangList.hpp"
#include "LanguagesSelectBrowser.hpp"
#include "../Controls/Application.h"
#include "../Prompts/ProgressWindow.h"
#include "../Prompts/PromptWindows.h"
#include "../FileOperations/fileops.h"
#include "../FileOperations/DirList.h"
#include "../Network/FileDownloader.h"
#include "../Network/URL_List.h"

static const char * LanguageFilesURL = "http://savegame-manager-gx.googlecode.com/svn/trunk/Languages/";

UpdateLanguagesTask::UpdateLanguagesTask(const std::string &Path, short Type)
	: path(Path), type(Type)
{
	result = false;
	running = true;
	
	ThreadedTaskHandler::Instance()->AddTask(this);
}

void UpdateLanguagesTask::Execute(void)
{
	if(!CreateSubfolder(path))
	{
		ShowError(tr("Could not create path: %s"), path.c_str());
		running = false;
		return;
	}

	if(!NetworkInitPrompt())
	{
		ShowError(tr("Network is not initiated."));
		running = false;
		return;
	}

	if(type == ALL)
	{
		if(ProgressWindow::Instance()->IsRunning())
			ProgressWindow::Instance()->SetTitle(tr("Getting Language list on:"));
		else
			StartProgress(tr("Getting Language list on:"));
		ProgressWindow::Instance()->SetMessage("code.google.com");
		
		char fullURL[300];
		char filepath[300];
		
		URL_List LinkList(LanguageFilesURL);
		int listsize = LinkList.GetURLCount();
		
		ProgressWindow::Instance()->SetTitle(tr("Downloading all Language Files:"));
		
		for (int i = 0; i < listsize; i++)
		{
			const char * filename = strrchr(LinkList.GetURL(i), '/');
			if(filename)
				filename++;
			else
				filename = LinkList.GetURL(i);
			
			if(!filename)
				continue;
			
			std::string FileExt = filename;
			int index = FileExt.find_last_of('.');
			if(index <= 0)
				continue;
			
			FileExt = FileExt.substr(index);
			if(!FileExt.compare("."))
				continue;
			
			ToLowerCase(FileExt);
			
			if (FileExt.empty() || CompareLanguageFiles(FileExt.c_str()))
				continue;
			
			snprintf(fullURL, sizeof(fullURL), "%s%s", LanguageFilesURL, filename);
			snprintf(filepath, sizeof(filepath), "%s/%s", path.c_str(), filename);
			
			int ret = DownloadFileToPath(fullURL, filepath, false);
			if(ret < 1024)
				ShowError(tr("Error when downloading file: %s"), filename);
		}
	}
	else if(type == INSTALLED)
	{
		if(ProgressWindow::Instance()->IsRunning())
			ProgressWindow::Instance()->SetTitle(tr("Updating Language Files:"));
		else
			StartProgress(tr("Updating Language Files:"));
		
		DirList Dir(path, ".lang");
		
		if(!Dir.GetFilecount())
		{
			ShowError(tr("No Language File found"));
			running = false;
			return;
		}
		
		char savepath[300];
		char codeurl[300];
		
		for(int i = 0; i < Dir.GetFilecount(); ++i)
		{
			snprintf(codeurl, sizeof(codeurl), "%s%s", LanguageFilesURL, Dir.GetFilename(i));
			snprintf(savepath, sizeof(savepath), "%s/%s", path.c_str(), Dir.GetFilename(i));
			
			int ret = DownloadFileToPath(codeurl, savepath, false);
			if(ret < 1024)
				ShowError(tr("Error when downloading file: %s"), Dir.GetFilename(i));
		}
	}
	else if(type == SELECTED)
	{
		if(ProgressWindow::Instance()->IsRunning())
			ProgressWindow::Instance()->SetTitle(tr("Downloading Language Files:"));
		else
			StartProgress(tr("Downloading Language Files:"));
		
		char savepath[300];
		char langurl[300];
		
		for (int i = 0; i < LangList.GetCount(); i++)
		{
			if (LangList.Needed(i))
			{
				snprintf(langurl, sizeof(langurl), "%s%s", LanguageFilesURL, LangList.GetFilename(i));
				snprintf(savepath, sizeof(savepath), "%s/%s", path.c_str(), LangList.GetFilename(i));
				
				int ret = DownloadFileToPath(langurl, savepath, false);
				if(ret < 1024)
					ShowError(tr("Error when downloading file: %s"), LangList.GetFilename(i));
			}
		}
	}
	
	sleep(1);
	
	//! reload language
	Settings.LoadLanguage(Settings.LanguageFile);
	
	result = true;
	running = false;
}
